function Cart() {

    //关闭购物车按钮
    const closeCartBtn = document.querySelector('.minicart-close')
    //遮罩层
    const overlay = document.querySelector('.offcanvas-overlay')
    //购物车容器
    const cartCon = document.querySelector('.minicart-content-box')
    //购物车商品容器，用于添加事件代理
    let cartListCon = document.querySelector('.minicart-item-wrapper')
    //购物车数据在localStorage里面的键
    const CART_DATA_KEY = "cartDataKey"

    const ctx = this
    this.cartGoodsList = []

    //打开购物车
    this.openCart = function (e) {
        try {
            e.preventDefault()
        } catch (err) {}
        document.body.classList.add('fix');
        document.querySelector(".minicart-inner").classList.add('show')
    }
    //关闭购物车
    this.closeCart = function (e) {
        try {
            e.preventDefault()
        } catch (err) {}
        document.body.classList.remove('fix');
        document.querySelector(".minicart-inner").classList.remove('show')
    };

    //购物车内部绑定事件
    function bindCartEvent() {
        //关闭购物车
        closeCartBtn.onclick = ctx.closeCart
        //遮罩层关闭购物车
        overlay.onclick = ctx.closeCart
        //购物车删除商品事件更新/绑定
        updateCartEvent()
    }


    //更新购物车DOM元素上面的事件
    function updateCartEvent() {
        //从新获购物车取商品列表容器
        cartListCon = document.querySelector('.minicart-item-wrapper')
        //从新绑定事件
        cartListCon.addEventListener('click', function (e) {
            //获取到点击的元素
            const target = e.target
            //获取事件类型
            const event = target.dataset.event
            //如果是删除
            if (event === "delete") {
                //获取iid
                const iid = target.dataset.iid
                //调用删除功能
                ctx.deleteFromCart(iid)
            }
        })
    }

    //格式化购物车数据
    function formatGoodsItem(goodsData) {
        const cartGoodsItem = {}
        cartGoodsItem.img = goodsData.show ? goodsData.show.img : goodsData.img
        cartGoodsItem.title = goodsData.title
        cartGoodsItem.price = goodsData.price
        cartGoodsItem.num = goodsData.num ? parseInt(goodsData.num) : 1
        cartGoodsItem.iid = goodsData.iid
        return cartGoodsItem
    }


    //购物车商品html片段生成
    function genCartListHtml() {
        const cartListHtmlArr = ctx.cartGoodsList.map(item => {
            return ` 
        <li class="minicart-item">
            <div class="minicart-thumb">
                <a href="product-details.html">
                    <img src="${item.img}" alt="${item.title}">
                </a>
            </div>
            <div class="minicart-content">
                <h3 class="product-name">
                    <a href="product-details.html">${item.title}</a>
                </h3>
                <p>
                    <span class="cart-quantity">${item.num} <strong>&times;</strong></span>
                    <span class="cart-price">￥${item.price}</span>
                </p>
            </div>
            <button class="minicart-remove" data-event="delete" data-iid="${item.iid}"><i class="lnr lnr-cross" data-event="delete" data-iid="${item.iid}"></i></button>
        </li>`
        })
        return cartListHtmlArr.join('')

    }

    //整个购物车渲染
    this.renderCart = function () {
        const cartListHtml = genCartListHtml(this.cartGoodsList)
        const cartInfo = computeCart(this.cartGoodsList)
        //商品总价
        const totalPrice = cartInfo.totalPrice
        //商品总量
        const totalNum = cartInfo.totalNum
        const html = `
        <div class="minicart-item-wrapper">
            <ul>
                ${cartListHtml}
            </ul>
        </div>

        <div class="minicart-pricing-box">
            <ul>
                <li>
                    <span>商品数量</span>
                    <span><strong>${totalNum}</strong></span>
                </li>
                <li class="total">
                    <span>总价</span>
                    <span><strong>￥${totalPrice}</strong></span>
                </li>
            </ul>
        </div>

        <div class="minicart-button">
            <a href="#"><i class="fa fa-shopping-cart"></i>查看购物车</a>
            <a href="#"><i class="fa fa-share"></i>结账</a>
        </div>
        `
        cartCon.innerHTML = html
        //更新事件
        updateCartEvent()
        //通过购物车数据列表到localStorage里面
        setStorage(CART_DATA_KEY, ctx.cartGoodsList)
        this.onrender(this.cartGoodsList, {
            totalNum,
            totalPrice
        })
    }

    //计算购物车总价和数量
    function computeCart() {
        let totalPrice = 0
        let totalNum = 0
        ctx.cartGoodsList.forEach(item => {
            totalPrice += item.price * item.num
            totalNum += item.num
        })
        return {
            totalPrice: totalPrice.toFixed(2),
            totalNum
        }
    }

    //向购物车添加商品
    this.addToCart = function (goodsData) {
        console.log('addTocart')
        //判断商品是否已经存在购物车里面
        const oldGoodsItem = this.cartGoodsList.find(item => item.iid === goodsData.iid)
        if (oldGoodsItem) {
            //商品已经存在购物车
            oldGoodsItem.num++
        } else {
            const cartItem = formatGoodsItem(goodsData)
            //把购物车数据添加到购物车数据列表
            this.cartGoodsList.push(cartItem)
        }
        //从新使用购物车列表数据渲染到页面
        this.renderCart()

    }



    //通过商品的iid查找商品在购物车数据栏的索引
    function searchCart(iid) {
        for (let i = 0; i < ctx.cartGoodsList.length; i++) {
            const item = ctx.cartGoodsList[i]
            if (iid === item.iid) {
                return i
            }
        }
        return -1
    }

    //在购物车内删除商品
    this.deleteFromCart = function (iid) {
        const i = searchCart(iid)
        if (i != -1) {
            //如果找到则删除
            ctx.cartGoodsList.splice(i, 1)
            ctx.renderCart()
        }
    }

    /**
     * 给localStorage设置数据
     * @param {string} key 
     * @param {Object} data 
     */
    function setStorage(key, data) {
        const dataStr = JSON.stringify(data)
        localStorage.setItem(key, dataStr)
    }
    /**
     * 从localStorage获取数据
     * @param {string}} key 
     */
    function getStorage(key) {
        const dataStr = localStorage.getItem(key)
        let data
        try {
            data = JSON.parse(dataStr)
        } catch (e) {
            return dataStr
        }
        return data
    }

    //初始化购物车数据，从localStorage里面恢复数据
    function initCartData() {
        return getStorage(CART_DATA_KEY) || []
    }

    //初始化购物车
    function initCart() {
        ctx.cartGoodsList = initCartData()
        bindCartEvent()

    }

    this.onrender = function (cartGoodsList, cartRes) {

    }

    initCart()

}

//实例化一个购物车
const cart = new Cart()

//打开购物车按钮
const openCartBtn = document.querySelector('.minicart-btn')
//购物车按钮数字
const cartIcon = document.querySelector('.minicart-btn .notification')
//更新购物车图片的数字
function updateCartIcon(num) {
    cartIcon.innerText = num
}


openCartBtn.onclick = cart.openCart
cart.onrender = function (cartGoodsItem, cartRes) {
    updateCartIcon(cartRes.totalNum)
}
cart.renderCart()